<?php
/**
 * 导入动作权限
 * User：liujun
 * Date：2022/3/5
 * Time：11:16 AM
 */

namespace Encore\Admin\Actions\Custom;

use Encore\Admin\Actions\Action;
use Encore\Admin\Actions\Response;
use Illuminate\Http\Request;

class PermissionCreateFromMenuAction extends Action
{
    protected $selector = '.permission-create-from-menu-action';
    protected array $actions = [
        'view'   => '查看',
        'create' => '新增',
        'edit'   => '编辑',
        'delete' => '删除',
    ];

    public $name = '添加权限';

    public function handle(Request $request): Response
    {
        $adminMenuId = $request->get('admin_menu_id');
        $menuId      = $request->get('menu_id');
        $actions     = array_filter($request->get('actions'));
        $menuModel   = config('admin.database.menu_model');
        $menu        = $menuModel::findOrFail($menuId);

        $creates = [];
        foreach ($actions as $action) {
            $create = [
                'admin_menu_id' => $adminMenuId,
                'name'          => $this->actions[$action] . '' . $menu->title,
                'slug'          => str_replace('-', '.', $menu->uri) . '.' . $action,
                'http_path'     => '/' . $menu->uri . '*',
            ];

            switch ($action) {
                case 'view':
                    $create['http_method'] = ['GET'];
                    break;
                case 'create':
                    $create['http_method'] = ['POST', 'GET'];
                    break;
                case 'edit':
                    $create['http_method'] = ['PUT', 'GET'];
                    break;
                case 'delete':
                    $create['http_method'] = ['DELETE', 'GET'];
                    break;
            }

            $create['http_method'] = implode(',', $create['http_method']);
            $creates[]             = $create;
        }

        if (count($creates) > 0) {
            $permissionModel = config('admin.database.permissions_model');
            $permissionModel::upsert($creates, ['slug'], ['name', 'http_path', 'http_method', 'admin_menu_id']);
        }

        return $this->response()->success('权限添加成功！')->refresh();
    }

    public function form()
    {
        $menuModel   = config('admin.database.menu_model');
        $menuOptions = $menuModel::whereNotNull('uri')
            ->orWhere('uri', '<>', '')
            ->pluck('title', 'id');

        $this->select('admin_menu_id', __('admin/admin_permission.admin_menu_id'))
            ->options(config('admin.database.menu_model')::parentOptions())
            ->rules('required');

        $this->select('menu_id', '预生成权限菜单')
            ->options($menuOptions)
            ->rules('required');

        $this->checkbox('actions', '操作动作')->options($this->actions)->rules('required');
    }

    public function html(): string
    {
        return '<a href="javascript:;" class="btn btn-sm btn-primary permission-create-from-menu-action"><i class="fa fa-plus"></i> 添加权限</a>';
    }
}
